package cn.qio.bootstrap;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;

import cn.qio.channel.handler.AbsChannelHandler;
import cn.qio.channel.session.SessionServer;
import cn.qio.event.Event;

public class TestMain {

	public static void main(String[] args) throws IOException {
		SessionServer sessionServer = new SessionServer();
		sessionServer.addHandler(new UserChannelHandler());
		sessionServer.start(5555);
	}

	static class UserChannelHandler extends AbsChannelHandler {

		@Override
		public void messageReceived(Event event) {
			ByteBuffer bb = (ByteBuffer) event.getData();
			CharBuffer cb = bb.asCharBuffer();
			while (cb.hasRemaining()) {
				System.out.println(cb.get());
			}
		}

		@Override
		public void messageSent(Event event) {
			SocketChannel sc = event.getChannelSession().getSocketChannel();
			if (sc.isOpen()) {
				ByteBuffer bb = ByteBuffer.wrap("hello".getBytes());
				try {
					sc.write(bb);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
